﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;     //引用请求委托的命名空间
using Microsoft.Extensions.Logging;  //引用日志的命名空间

namespace IotWeek2Day9.WebApi.Middlewares
{
    /// <summary>
    /// 请求日志中间件
    /// </summary>
    public class RequestLogMiddleware
    {
        //下一个请求委托
        private readonly RequestDelegate _next;
        private readonly ILogger<RequestLogMiddleware> _logger;  //记录日志

        public RequestLogMiddleware(RequestDelegate next, ILogger<RequestLogMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        /// <summary>
        /// 公开方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                Stopwatch stopwatch = new Stopwatch();  //Stopwatch秒表
                stopwatch.Start(); //开始计时

                await _next(context); //调用下一个请求委托

                stopwatch.Stop();  //停止计时

                string requestUrl = context.Request.Path; //获取请求的URL路径

                _logger.LogInformation($"请求{requestUrl}，消耗了{stopwatch.ElapsedMilliseconds}毫秒"); //在控制台（黑窗）输出性能日志
            }
            catch (Exception ex)
            {
                string requestUrl = context.Request.Path; //获取请求的URL路径
                _logger.LogError($"请求{requestUrl}发生了异常，错误是{ex.Message}");
            }
        }
    }
 
}
